// 首页接口

package api

import (
	"api/common/logger"
	"api/common/orm"
	"api/common/web"
	"api/models"
	"net/http"
	"strings"
	"time"
)

// @TagName 首页接口
// @Controller HomeController
type HomeController struct{}

// @Title 首页数据
// @Route /home/data --> Data
// @Method post
func (this *HomeController) Data(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)

	// 获取文章数据
	type Content struct {
		Id      uint32 `json:"id"`
		Title   string `json:"title"`
		MarkImg string `json:"markImg"`
	}
	dataContent := []Content{}
	sql := "select id, title, mark_img" +
		" from info_content" +
		" where recommend=true" +
		" order by sequ desc" +
		" limit 10"
	conn := orm.NewOrm()
	_, err := conn.Raw(sql).QueryRows(&dataContent)
	if err != nil {
		logger.Error("获取文章数据发生错误", err)
		web.ServeJSON(w, web.JsonMsg{false, "获取文章数据发生错误" + err.Error(), 1})
		return
	}

	// 获取通知公告数据
	type Notice struct {
		Id    uint32 `json:"id"`
		Title string `json:"title"`
	}
	dataNotice := []Notice{}
	sql = "select id, title" +
		" from info_notice" +
		" where now() >= begin_time and now() <= end_time" +
		" order by sequ desc" +
		" limit 10"
	_, err = conn.Raw(sql).QueryRows(&dataNotice)
	if err != nil {
		logger.Error("获取通知公告数据发生错误", err)
		web.ServeJSON(w, web.JsonMsg{false, "获取通知公告数据发生错误" + err.Error(), 1})
		return
	}

	// 获取轮播图数据
	type Image struct {
		Id    uint32 `json:"id"`
		Title string `json:"title"`
		Src   string `json:"src"`
	}
	dataBanner := []Image{}
	sql = "select id, title, src" +
		" from info_image" +
		" order by sequ desc" +
		" limit 10"
	_, err = conn.Raw(sql).QueryRows(&dataBanner)
	if err != nil {
		logger.Error("获取轮播图数据发生错误", err)
		web.ServeJSON(w, web.JsonMsg{false, "获取轮播图数据发生错误" + err.Error(), 1})
		return
	}

	result := map[string]interface{}{}
	result["success"] = true
	result["status"] = 0
	result["msg"] = "查询成功"
	result["dataContent"] = dataContent
	result["dataNotice"] = dataNotice
	result["dataBanner"] = dataBanner
	result["showSignUpButton"] = true

	// 额外返回是否显示“我要报名”按钮
	value := ""
	sql = "select `value` from basic_global_set where `name` = ?"
	err = conn.Raw(sql, "signUpTimeFrame").QueryRow(&value)
	if err != nil {
		logger.Error(err)
		web.ServeJSON(w, result)
		return
	}

	if len(value) == 11 {
		// 07-01,08-31
		dateFmt := "2006-01-02"
		now := time.Now()
		year := orm.ToStr(now.Year())
		valueData := strings.Split(value, ",")
		if len(valueData) == 2 {
			beginDate := year + "-" + valueData[0]
			endDate := year + "-" + valueData[1]
			d0, _ := time.Parse(dateFmt, beginDate)
			d1, _ := time.Parse(dateFmt, endDate)
			isBetween := now.After(d0) && now.Before(d1)
			result["showSignUpButton"] = isBetween
		}
	}

	web.ServeJSON(w, result)
}

// @Title 内容详情数据
// @Route /home/contentDetail --> ContentDetail
// @Param {"id":0}
// @Method post
func (this *HomeController) ContentDetail(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	inputJson, msg := web.ExemptTokenCheckRequest(r)
	if msg != nil {
		web.ServeJSON(w, msg)
		return
	}

	id := inputJson["id"]
	if id == nil || id == "" {
		web.ServeJSON(w, web.JsonMsg{false, "内容id不能为空", 1})
		return
	}

	// 浏览次数+1
	conn := orm.NewOrm()
	sql := "update info_content set browse_num=browse_num+1 where id=?"
	_, err := conn.Raw(sql, id).Exec()
	if err != nil {
		logger.Error("更新浏览次数发生错误", err)
		web.ServeJSON(w, web.JsonMsg{false, "更新浏览次数发生错误" + err.Error(), 1})
		return
	}

	// 获取详情信息
	model := &models.Content{}
	sql = "select * from info_content where id=?"
	err = conn.Raw(sql, id).QueryRow(model)
	if err != nil {
		if strings.Index(err.Error(), "no row found") == -1 {
			logger.Error("获取详情信息发生错误", err)
			web.ServeJSON(w, web.JsonMsg{false, "获取详情信息发生错误" + err.Error(), 1})
			return
		}

		web.ServeJSON(w, web.JsonMsg{false, "未找到相关记录", 1})
		return
	}

	result := map[string]interface{}{}
	result["success"] = true
	result["status"] = 0
	result["msg"] = "查询成功"
	result["model"] = model
	web.ServeJSON(w, result)
}

// @Title 通知公告详情数据
// @Route /home/noticeDetail --> NoticeDetail
// @Param {"id":0}
// @Method post
func (this *HomeController) NoticeDetail(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	inputJson, msg := web.ExemptTokenCheckRequest(r)
	if msg != nil {
		web.ServeJSON(w, msg)
		return
	}

	id := inputJson["id"]
	if id == nil || id == "" {
		web.ServeJSON(w, web.JsonMsg{false, "内容id不能为空", 1})
		return
	}

	// 获取详情信息
	model := &models.Notice{}
	sql := "select * from info_notice where id=?"
	conn := orm.NewOrm()
	err := conn.Raw(sql, id).QueryRow(model)
	if err != nil {
		if strings.Index(err.Error(), "no row found") == -1 {
			logger.Error("获取详情信息发生错误", err)
			web.ServeJSON(w, web.JsonMsg{false, "获取详情信息发生错误" + err.Error(), 1})
			return
		}

		web.ServeJSON(w, web.JsonMsg{false, "未找到相关记录", 1})
		return
	}

	result := map[string]interface{}{}
	result["success"] = true
	result["status"] = 0
	result["msg"] = "查询成功"
	result["model"] = model
	web.ServeJSON(w, result)
}
